<?php

/**
 * wap共用类
 *
 * @author 周剑锋 <camfee@foxmail.com>
 *
 * $Id$
 */

namespace Mobile;

use Common\Tags;
use Recommend\UserScore;
use Encrypt\Blowfish;
use Passport\Login;

class Wap
{
    /**
     * 获取一个唯一设备ID
     *
     * @param int $appid App类型ID wap
     * @return string
     */
    public static function getDeviceId($appid = 3)
    {
        if (!empty($_COOKIE['duid'])) {
            $duid = $_COOKIE['duid'];
        } else {
            $duid = $appid . sprintf('%02x', crc32(php_uname('n'))) . str_replace('.', '', uniqid('', true));
            setcookie('duid', $duid, time() + 315360000, '/');

            $channel = loadconf('article/channel');
            $channels = $channel['channels'];
            $ctag = $ctag2 = $ctagname = [];
            foreach ($channels as $v) {
                $ctagname[$v['name']] = $v['name'];
            }
            if (!empty($ctagname)) {
                $ctag2 = Tags::getTagsByName($ctagname);
            }
            $ctag = $ctag + $ctag2;
            if (count($ctag) > 6) {
                $ctag = array_slice($ctag, 0, 6);
            }
            UserScore::subscribeTag($duid, array_values($ctag));
        }
        return $duid;
    }

    /**
     * App登录信息互通
     *
     * @return bool|int
     */
    public static function init()
    {
        $auth = trim($_SERVER['HTTP_AUTH']);
        if (empty($auth)) {
            $auth = trim($_GET['auth']);
        }
        $decode = Blowfish::decode($auth);

        if ($decode != false) {
            $arr = explode('|', $decode);
            if (count($arr) == 4) {
                $uid = $arr[1];

                Login::initSession([
                    'UserId' => $uid,
                    'UserName' => '',
                ]);
                Login::initCookie($uid, true);

                return $uid;
            }
        } else {
            unset($_SESSION['UserId']);
            unset($_SESSION['UserName']);
            setcookie('_auth', '', 1);
            setcookie('_uid', '', 1);
        }
        return false;
    }

    public static function getAuth()
    {
        if (!isset($_SERVER['HTTP_AUTH'])) {
            return '';
        }

        $auth = trim($_SERVER['HTTP_AUTH']);
        if (empty($auth)) {
            $auth = trim($_GET['auth']);
        }
        return $auth;
    }
}